<?php
namespace Demo\Controller;

use Common\Controller\DemoBaseController;

/**
 * 后台登录
 * User: Richard
 * Date: 2020/3/15
 * Time: 11:23
 */
class LoginController extends DemoBaseController
{
    private $userModel;

    function __construct()
    {
        parent::__construct();
        $this->userModel = M('users');
    }

    /**
     * h后台登录
     */
    public function login()
    {
        $username = I('post.username');
        if (empty($username)) {
            $this->returnerror('', '请输入账号');
        }
        $password = I('password');
        if (empty($password)) {
            $this->returnerror('', '请输入密码');
        }

        $userInfo = $this->userModel->where(['username' => $username])->field('id,password,nickname,role_id,status')->find();
        if (empty($userInfo)) {
            $this->returnerror('', '账号不存在');
        }
        if (!sp_compare_password($password, $userInfo['password'])) {
            $this->returnerror('', '账号或者密码错误');
        }
        if ($userInfo['status'] == 0) {
            $this->returnerror('', '账号已被冻结');
        }

        //登录成功

        session('admin_id', $userInfo['id']);
        session('nickname', $userInfo['nickname']);
        session('role_id', $userInfo['role_id']);

        $this->userModel->where(['id' => $userInfo['id']])->save(['last_login_time' => date('Y-m-d H:i:s')]);

        cookie('demo_admin_user', $username, 3600 * 24 * 30);

        // todo 登录成功跳转后台首页
    }
}